<template>
  <div class="swiper-container">
    <div class="swiper-wrapper">
      <div class="swiper-slide" v-for="(item, index) in options" :key="index">
        <div class="full-slide" :style="{ backgroundImage: `url(${item.url})` }"></div>
      </div>
    </div>
  </div>
</template>

<script>
import Swiper from 'swiper';
import 'swiper/dist/css/swiper.min.css';

export default {
  name: 'baseSwipe',
  props: {
    options: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      autoplay: 10 * 1000,
      swiper: null
    };
  },
  watch: {
    options: {
      handler() {
        this.updateSwiper();
      },
      deep: true
    }
  },
  mounted() {
    this.initSwiper();
  },
  beforeDestroy() {
    if (this.swiper) {
      this.swiper.destroy(true, true);
    }
  },
  methods: {
    initSwiper() {
      this.swiper = new Swiper('.swiper-container', {
        loop: true, // 启用循环
        slidesPerView: 1, // 每次显示一张幻灯片
        init: true, // 初始化时启动Swiper
        effect: 'fade', // 设置效果为淡出
        fadeEffect: {
          crossFade: true
        },
        updateTranslate: true, // 确保Swiper在初始化时更新位移
        autoplay: {
          delay: this.autoplay, // 自动播放的时间间隔
          stopOnLastSlide: false, // 在最后一张幻灯片时不停止自动播放
          disableOnInteraction: false // 用户交互后不禁用自动播放
        },
        speed: 300,
        preloadImages: false, // 禁用预加载所有图片
        updateOnImagesReady: true, // 图片加载完成后更新
        watchSlidesProgress: false,
        watchSlidesVisibility: false,
        spaceBetween: 10,
        initialSlide: 0, // 设置初始显示的幻灯片索引
        observer: true, // 修改Swiper自身或子元素时，自动初始化Swiper
        observeParents: true, // 修改Swiper的父元素时，自动初始化Swiper
        observeSlideChildren: true, // 修改Swiper的子元素时，自动初始化Swiper
        pagination: {
          el: '.swiper-pagination', // 分页器元素
          clickable: true // 分页器可点击
        },
        lazy: {
          loadPrevNext: true, // 预加载前后幻灯片
          loadPrevNextAmount: 2 // 预加载当前 slide 前后各 2 张图片
        },
        navigation: {
          nextEl: '.swiper-button-next', // 下一个按钮元素
          prevEl: '.swiper-button-prev' // 上一个按钮元素
        }
      });
    },
    updateSwiper() {
      if (this.swiper) {
        this.swiper.destroy(true, true); // 销毁当前实例
      }
      this.$nextTick(() => {
        this.initSwiper(); // 重新创建实例
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.swiper-container {
  height: 100%;
  overflow: hidden;
  .full-slide {
    background-size: contain;
    background-repeat: no-repeat;
    background-position: center;
    height: 100%;
    img {
      display: block;
      width: 100%;
      object-fit: contain;
    }
  }
}
</style>
